<?php

namespace App\Http\Controllers\API;

use App\Clock;
use App\Http\Server\Basic;
use App\On_off;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Exception;

class ClockController extends Controller
{
    /**
     * 控制方法
     *
     * @param $device_ids
     * @return bool
     */
    private static function control($device_ids) {

        foreach (explode(",", $device_ids) as $device_id) {

            try {

                if ($device = SwitchController::getSwitch($device_id)) {

                    /* tcp 控制 */

                    $control = On_off::find($device->id);

                    $code = $control['code'];

                    Basic::sendData("CONTROL/:$code", env('TCP_SERVER_HOST'), env('TCP_SERVER_PORT'));
                }

            } catch (Exception $exception) {

                Basic::errorLogs("clock control error: ".$exception->getMessage());

                return false;
            }

        }

        return true;
    }

    /**
     * 初始化
     * @return \Illuminate\Http\JsonResponse
     */
    public function index() {

        $data = Clock::get();

        foreach ($data as $key => $info) {

            $data[$key]['beginDeviceLists'] = empty($info['begin_device_ids']) ? [] : explode(",", $info['begin_device_ids']);
            $data[$key]['endDeviceLists'] = empty($info['end_device_ids']) ? [] : explode(",", $info['end_device_ids']);

        }

        $switch = On_off::all();

        return self::msgJson('OK', '获取成功', $data, $switch);
    }

    /**
     * 新建方法
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function create() {

        Clock::create();

        return self::msgJson('OK', '新建成功');
    }

    /**
     * 更新方法
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request) {

        $info = $request->all();
        $time = Clock::find($info['id']);
        $time->name = $info['name'];
        $time->value = $info['value'];
        $time->begin_device_ids = sizeof($info['beginDeviceLists'])?implode(",", $info['beginDeviceLists']):NULL;
        $time->end_device_ids = sizeof($info['endDeviceLists'])?implode(",", $info['endDeviceLists']):NULL;
        $time->time = $info['time'];
        $time->save();

        return self::msgJson('OK', '更新成功');
    }

    /**
     * 启动计时任务
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function clockSwitch(Request $request) {

        $info = $request->all();

        try {

            $clock = Clock::find($info['id']);

            if ($clock['status'] == Clock::CLOSE) {

                $txt = fopen('./server.php', "w"); // 覆盖写入，文件不存在则新增
                fwrite($txt, '<?php set_time_limit('.($clock['time']+10).'); sleep('.$clock['time'].
                    '); shell_exec("curl '.env('APP_URL').'/api/finishControl?id='.$clock['id'].'"); ?>');
                fclose($txt);

                exec("(php ./server.php > /dev/null 2>&1 &)");

                self::control($clock['begin_device_ids']);

                $clock->status = Clock::OPEN; // 1 代表启动

                $clock->save();

            } else {

                return self::msgJson('FAIL', '上一次任务还未完成');

            }

            return self::msgJson('OK', '控制成功');

        } catch (Exception $exception) {

            Basic::errorLogs("function clockSwitch error: ".$exception->getMessage());

        }

        return self::msgJson('FAIL', '控制失败');

    }

    /**
     * 定时结束方法
     * @param Request $request
     * @return bool|\Illuminate\Http\JsonResponse
     */
    public function finishControl(Request $request)
    {
        $info = $request->all();
        if (($clock = Clock::find($info['id'])) && (self::control($clock['end_device_ids']))) {
            $clock->status = Clock::CLOSE;
            $clock->save();
            return self::msgJson('OK', '控制成功');
        }
        Basic::errorLogs("finish control 控制出错");
        return self::msgJson('ERROR', '控制出错');
    }

    /**
     * 删除方法
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(Request $request) {
        $id = $request->get('id');
        if (isset($id) && $id) {
            Clock::destroy($id);
            return self::msgJson('OK', '删除成功');
        }
        return self::msgJson('FALSE', '删除失败');
    }
}
